<?php

namespace Kateba\SiteBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Kateba\SiteBundle\Entity\Question;
use Kateba\SiteBundle\Entity\Answer;

class QuestionController extends Controller {

    /**
     * add question
     * @author ahmed
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function addQuestionAnswerAction($questionId, $answer, $answerNotify) {
        if (FALSE === $this->get('security.context')->isGranted('ROLE_USER')) {
            return new Response('failed');
        }
        //get logedin user objects
        $user = $this->get('security.context')->getToken()->getUser();
        //get the entity manager
        $em = $this->getDoctrine()->getEntityManager();
        $questionRepo = $em->getRepository('KatebaSiteBundle:Question');

        $question = $questionRepo->find($questionId);
        if (!$question) {
            return new Response('failed');
        }

        $newAnswer = new Answer();
        $newAnswer->setUser($user);
        $newAnswer->setQuestion($question);
        $newAnswer->setAnswer($answer);

        if ($user->getId() == $question->getUser()->getId()) {
            $newAnswer->setIsAdmin(FALSE);
        } elseif (TRUE === $this->get('security.context')->isGranted('ROLE_ADMIN')) {
            $newAnswer->setIsAdmin(TRUE);
        }

        $em->persist($newAnswer);
        $user->setAnswerNotify($answerNotify);
        $em->flush();

        if ($user->getId() == $question->getUser()->getId()) {
            //send email to the admin
            $subject = 'Educino - New Question Answer';
            $message = $this->renderView('KatebaSiteBundle:Question:addQuestionAnswerEmail.html.twig', array(
                'user' => $user,
                'question' => $question,
                'newAnswer' => $newAnswer
            ));
            $headers = 'From: Educino <' . $this->container->getParameter('admin_notifications_email') . '>' . "\r\n";
            $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
            mail($this->container->getParameter('admin_notifications_email'), $subject, $message, $headers);

//            $message = \Swift_Message::newInstance()
//                    ->setSubject('Educino - New Question Answer')
//                    ->setFrom($this->container->getParameter('admin_notifications_email'))
//                    ->setTo($this->container->getParameter('admin_notifications_email'))
//                    ->setBody($this->renderView('KatebaSiteBundle:Question:addQuestionAnswerEmail.html.twig', array(
//                        'user' => $user,
//                        'question' => $question,
//                        'newAnswer' => $newAnswer
//                    )))
//            ;
//            //send the mail
//            $this->get('mailer')->send($message);
        } elseif (TRUE === $this->get('security.context')->isGranted('ROLE_ADMIN') && $question->getUser()->getAnswerNotify() == 1) {
            //send email to the admin
            $subject = 'Educino - New Question Answer';
            $message = $this->renderView('KatebaSiteBundle:Question:adminAddQuestionAnswerEmail.html.twig', array(
                'user' => $user,
                'question' => $question,
                'newAnswer' => $newAnswer
            ));
            $headers = 'From: Educino <' . $this->container->getParameter('admin_notifications_email') . '>' . "\r\n";
            $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
            mail($question->getUser()->getEmail(), $subject, $message, $headers);

//            $message = \Swift_Message::newInstance()
//                    ->setSubject('Educino - New Question Answer')
//                    ->setFrom($this->container->getParameter('admin_notifications_email'))
//                    ->setTo($question->getUser()->getEmail())
//                    ->setBody($this->renderView('KatebaSiteBundle:Question:adminAddQuestionAnswerEmail.html.twig', array(
//                        'user' => $user,
//                        'question' => $question,
//                        'newAnswer' => $newAnswer
//                    )))
//            ;
//            //send the mail
//            $this->get('mailer')->send($message);
        }



        return $this->render('KatebaSiteBundle:Question:addQuestionAnswer.html.twig', array(
                    'answer' => $newAnswer
        ));
    }

    /**
     * list all question answers
     * @author ahmed
     * @param int $id
     */
    public function getAllQuestionAnswersAction($id) {
        $em = $this->getDoctrine()->getEntityManager();
        $questionRepo = $em->getRepository('KatebaSiteBundle:Question');

        $question = $questionRepo->find($id);
        if (!$question) {
            return new Response('failed');
        }

        $answers = $question->getAnswers();
        return $this->render('KatebaSiteBundle:Question:getAllQuestionAnswers.html.twig', array(
                    'answers' => $answers
        ));
    }

    /**
     * show question
     * @author ahmed
     * @param int $id
     */
    public function showQuestionAction($id, $_locale) {
        $em = $this->getDoctrine()->getEntityManager();
        $questionRepo = $em->getRepository('KatebaSiteBundle:Question');
        $answerRepo = $em->getRepository('KatebaSiteBundle:Answer');

        $question = $questionRepo->find($id);
        if (!$question) {
            throw $this->createNotFoundException('Unable to find this question.');
        }

        //get question answers
        $answers = array_reverse($answerRepo->getQuestionAnswers($id, $this->container->getParameter('question_page_answers_number')));
        $answersCount = $answerRepo->countQuestionAnswers($id);

        //check if owner or admin
        $checkFlag = FALSE;
        if (TRUE === $this->get('security.context')->isGranted('ROLE_USER')) {
            //get logedin user objects
            $user = $this->get('security.context')->getToken()->getUser();
            if ($user->getId() == $question->getUser()->getId()) {
                $checkFlag = TRUE;
            } elseif (TRUE === $this->get('security.context')->isGranted('ROLE_ADMIN')) {
                $checkFlag = TRUE;
            }
        }

        return $this->render('KatebaSiteBundle:Question:showQuestion.html.twig', array(
                    'locale' => $_locale,
                    'question' => $question,
                    'answers' => $answers,
                    'question_page_answers_number' => $this->container->getParameter('question_page_answers_number'),
                    'answersCount' => $answersCount,
                    'checkFlag' => $checkFlag
        ));
    }

    /**
     * add question
     * @author ahmed
     * @param string $question
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function addQuestionAction($question, $questionDetails, $answerNotify) {
        //get the session
        $session = $this->get('session');
        if (FALSE === $this->get('security.context')->isGranted('ROLE_USER')) {
            //set the question in session
            $session->set('sessionQuestion', $question);
            if ($questionDetails)
                $session->set('sessionQuestionDetails', $questionDetails);
            return new Response('login');
        }
        //get logedin user objects
        $user = $this->get('security.context')->getToken()->getUser();
        //get the entity manager
        $em = $this->getDoctrine()->getEntityManager();
        $newQuestion = new Question();
        $newQuestion->setUser($user);
        $newQuestion->setQuestion($question);
        if ($questionDetails)
            $newQuestion->setQuestionDetails($questionDetails);

        $em->persist($newQuestion);
        $user->setAnswerNotify($answerNotify);
        $em->flush();

        //remove comment session
        $session->remove('sessionQuestion');

        //send email to the admin
        $subject = 'Educino - New Question';
        $message = $this->renderView('KatebaSiteBundle:Question:addQuestionEmail.html.twig', array(
            'user' => $user,
            'question' => $newQuestion
        ));
        $headers = 'From: Educino <' . $this->container->getParameter('admin_notifications_email') . '>' . "\r\n";
        $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
        mail($this->container->getParameter('admin_notifications_email'), $subject, $message, $headers);

//        $message = \Swift_Message::newInstance()
//                ->setSubject('Educino - New Question')
//                ->setFrom($this->container->getParameter('admin_notifications_email'))
//                ->setTo($this->container->getParameter('admin_notifications_email'))
//                ->setBody($this->renderView('KatebaSiteBundle:Question:addQuestionEmail.html.twig', array(
//                    'user' => $user,
//                    'question' => $newQuestion
//                )))
//        ;
//        //send the mail
//        $this->get('mailer')->send($message);

        return $this->render('KatebaSiteBundle:Question:addQuestion.html.twig', array(
                    'question' => $question
        ));
    }

    /**
     * list questions
     * @author ahmed
     * @param string $_locale
     * @param \Symfony\Component\HttpFoundation\Request $request
     */
    public function listQuestionsAction($_locale, Request $request) {
        //get the session
        $session = $this->get('session');
        //set the url in session
        $session->set('redirectUrl', $this->generateUrl('list_questions', array('_locale' => $_locale)));

        $em = $this->getDoctrine()->getEntityManager();
        $questionRepo = $em->getRepository('KatebaSiteBundle:Question');

        $itemsPerPage = $this->container->getParameter('number_of_questions_per_page');
        $page = $request->get('page', 1);
        $questionTitle = $request->get('question');

        $data = $questionRepo->getAllQuestions($page, $itemsPerPage, $questionTitle);
        $entities = $data['entities'];
        $count = $data['count'];
        //calculate the last page number
        $lastPageNumber = (int) ($count / $itemsPerPage);
        if (($count % $itemsPerPage) > 0) {
            $lastPageNumber++;
        }

        return $this->render('KatebaSiteBundle:Question:listQuestions.html.twig', array(
                    'locale' => $_locale,
                    'questions' => $entities,
                    'page' => $page,
                    'lastPageNumber' => $lastPageNumber,
                    'questionTitle' => $questionTitle
        ));
    }

}
